package sys

import (
	"encoding/json"
	"fmt"

	"gitee.com/zfd81/dbrs/store"
)

type MetadataType uint32

const (
	Type_Database MetadataType = iota
	Type_Table
)

// Nameable is something that has a name.
type Nameable interface {
	// Name returns the name.
	Name() string

	// Comment returns the comment.
	Comment() string
}

type Metadata interface {
	Nameable
	MType() MetadataType
	Store() error
	Load() error
	Remove() error
}

func StoreMetadata(md Metadata) error {
	bytes, err := json.Marshal(md)
	if err != nil {
		return err
	}
	switch md.MType() {
	case Type_Table:
		return store.Put(store.Table_Metadata, []byte(md.Name()), bytes)
	case Type_Database:
	}
	return fmt.Errorf("Metadata type error")
}

func LoadMetadata(md Metadata) error {
	var bytes []byte
	var err error
	switch md.MType() {
	case Type_Table:
		bytes, err = store.Get(store.Table_Metadata, []byte(md.Name()))
	case Type_Database:
	default:
		return fmt.Errorf("Metadata type error")
	}
	if err != nil {
		return err
	}
	return json.Unmarshal(bytes, md)
}

func RemoveMetadata(md Metadata) error {
	switch md.MType() {
	case Type_Table:
		return store.Delete(store.Table_Metadata, []byte(md.Name()))
	case Type_Database:
	}
	return fmt.Errorf("Metadata type error")
}
